package com.yunche.yunchebusiness.mvp.presenter

import android.annotation.SuppressLint
import com.alibaba.fastjson.JSONObject
import com.yunche.yunchebusiness.base.mvp.BasePresenter
import com.yunche.yunchebusiness.mvp.contract.FinanceContract
import com.yunche.yunchebusiness.mvp.model.FinanceModel
import com.yunche.yunchebusiness.network.RequestJson
import com.yunche.yunchebusiness.network.exception.ErrorStatus
import com.yunche.yunchebusiness.network.exception.ExceptionHandle
import okhttp3.RequestBody

/**
 * Create by Crcker on 2018/12/27 20:32
 * Email: Crcker@163.com
 */


class FinancePresenter : BasePresenter<FinanceContract.View>(), FinanceContract.Presenter {
    private val model by lazy {
        FinanceModel()
    }

    @SuppressLint("CheckResult")
    override fun getMoney(bankId: Int, sum: Float, type: Int) {

        var para = JSONObject()
        para["bankId"] = bankId
        para["sum"] = sum
        para["type"] = type

        mRootView?.showLoading()

        var disposable = model.getMoney(RequestJson.getRequestBody(para.toJSONString()))
            .subscribe({
                mRootView!!.apply {
                    hideLoading()
                    if (it.resultCode == ErrorStatus.SUCCESS) {
                        getMoneySuccess()
                    } else {
                        showError(it.message!!)
                    }
                }
            }, {
                mRootView?.hideLoading()
                mRootView?.showError(ExceptionHandle.handleException(it))
            })
        addSubscription(disposable)
    }

    override fun getTotalPrice() {
        checkViewAttached()
        mRootView?.showLoading()
        var disposable = model.getTotalPrice()
            .subscribe({
                mRootView!!.apply {
                    hideLoading()
                    if (it.resultCode == ErrorStatus.SUCCESS) {
                        getTotalPriceSuccess(it.datas!!)
                    } else {
                        showError(it.message!!)
                    }
                }
            }, {
                mRootView?.hideLoading()
                mRootView?.showError(ExceptionHandle.handleException(it))
            })

        addSubscription(disposable)
    }

    override fun getBankList(requestBody: RequestBody) {
        checkViewAttached()
        mRootView?.showLoading()
        var disposable = model.getBankList(requestBody)
            .subscribe({
                mRootView!!.apply {
                    hideLoading()
                    if (it.resultCode == ErrorStatus.SUCCESS) {
                        getBankListSuccess(it.datas!!)
                    } else {
                        showError(it.message!!)
                    }
                }
            }, {
                mRootView?.hideLoading()
                mRootView?.showError(ExceptionHandle.handleException(it))
            })

        addSubscription(disposable)
    }
}